<template>
  <div class="container">
    <header>
      <h1>{{ title }}</h1>
      <div class="header-controls">
        <div class="selection-mode">
          <button
            class="mode-btn"
            :class="{ active: selectionMode === 'single' }"
            @click="changeMode('single')"
          >单选模式</button>
          <button
            class="mode-btn"
            :class="{ active: selectionMode === 'multiple' }"
            @click="changeMode('multiple')"
          >多选模式</button>
        </div>
        <div class="search-box">
          <i class="fas fa-search search-icon"></i>
          <el-input clearable type="text" :placeholder="searchPlaceholder" v-model="searchTerm" />
        </div>
      </div>
    </header>

    <div class="content" style="flex:1;min-height:0;" :id="getHeight">
      <div v-if="isShowCategorie" class="sidebar">
        <ul class="category-list">
          <li
            v-for="category in categories"
            :key="category.id"
            class="category-item"
            :class="{ active: selectedCategory === category.id }"
            @click="selectCategory(category.id)"
          >
            <i :class="category.icon"></i>
            {{ category.name }}
          </li>
        </ul>
      </div>

      <div class="main-content flex col">
        <div class="devices-header">
          <h2>{{ listTitle }}</h2>
          <div class="devices-count">共找到 {{ filteredDevices.length }} 个设备</div>
        </div>

        <!-- 替换为表格布局 -->
        <div class="table-area f1" style="overflow:auto;border-top:1px solid #eee;">
          <el-table
            ref="deviceTable"
            @select="select"
            @select-all="selectAll"
            :data="filteredDevices"
            style="width: 100%;"
            size="medium"
          >
            <!-- 选择列（单选/多选切换） -->
            <el-table-column width="55">
              <template slot-scope="scope">
                <el-checkbox
                  v-model="scope.row.selected"
                  @change="handleSelectionChange(scope.row)"
                ></el-checkbox>
              </template>
            </el-table-column>

            <!-- 设备字段列（对应截图2的表头） -->
            <el-table-column label="集团设备卡编号" prop="integratedDeviceCardNumber" min-width="120" />
            <el-table-column label="设备标识" prop="deviceLabel" min-width="100" />
            <el-table-column label="在用地点" prop="usageLocation" min-width="100" />
            <el-table-column label="生产厂家" prop="mfr" min-width="100" />
            <el-table-column label="厂家编号" prop="mfrNo" min-width="100" />
          </el-table>
        </div>

        <div v-if="filteredDevices.length === 0" class="no-devices">{{ noDataText }}</div>
      </div>
    </div>

    <div class="footer">
      <div class="selected-info">
        已选择
        <span class="selected-count">{{ selectedDevices.length }}</span> 个设备
      </div>
      <div class="footer-buttons">
        <button class="cancel-btn" @click="handleCancel">取消</button>
        <button
          class="confirm-btn"
          :disabled="selectedDevices.length === 0"
          @click="confirmSelection"
        >{{ confirmButtonText }}</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "DeviceSelection",
  props: {
    // 基础配置
    title: {
      type: String,
      default: "选择设备"
    },
    isShowCategorie: {
      type: Boolean,
      default: false
    },
    listTitle: {
      type: String,
      default: "设备列表"
    },
    searchPlaceholder: {
      type: String,
      default: "搜索设备名称或编号..."
    },
    confirmButtonText: {
      type: String,
      default: "确定"
    },
    noDataText: {
      type: String,
      default: "未找到符合条件的设备"
    },

    // 数据
    categories: {
      type: Array,
      default: () => [
        { id: "all", name: "全部设备", icon: "fas fa-th-list" },
        { id: "demo", name: "演示用设备", icon: "fas fa-tv" },
        { id: "production", name: "生产设备", icon: "fas fa-industry" },
        { id: "electronic", name: "电子设备", icon: "fas fa-laptop" },
        { id: "transport", name: "运输工具", icon: "fas fa-truck" },
        { id: "instrument", name: "仪器及试验设备", icon: "fas fa-flask" },
        { id: "tools", name: "工具仪器及生产用品", icon: "fas fa-tools" },
        { id: "road", name: "一期扩建道路", icon: "fas fa-road" },
        { id: "land", name: "土地、使用权", icon: "fas fa-landmark" },
        { id: "decoration", name: "装修工程", icon: "fas fa-paint-roller" },
        { id: "office", name: "办公设备", icon: "fas fa-print" },
        { id: "other", name: "其他固定资产", icon: "fas fa-cube" },
        { id: "building", name: "建筑物", icon: "fas fa-building" },
        { id: "server1", name: "11111", icon: "fas fa-server" },
        { id: "server2", name: "2222222", icon: "fas fa-server" },
        { id: "server3", name: "333333", icon: "fas fa-server" },
        { id: "server4", name: "444444", icon: "fas fa-server" },
        { id: "server5", name: "555555", icon: "fas fa-server" },
        { id: "server", name: "x86服务器", icon: "fas fa-server" }
      ]
    },
    devices: {
      type: Array,
      default: () => [
        {
          integratedDeviceCardNumber: "11", // 集团设备卡编号
          financialNumber: "001007",
          startDate: "1901-01-01",
          deviceLabel: "演示用设备", // 设备标识
          deviceOriginalValue: 100,
          usageLocation: "2", // 在用地点
          mfr: "1", // 生产厂家
          mfrNo: "1", // 厂家编号
          selected: true
        },
        {
          integratedDeviceCardNumber: "112",
          financialNumber: "001008",
          startDate: "1901-01-01",
          deviceLabel: "演示用设备",
          deviceOriginalValue: 100,
          usageLocation: "152",
          mfr: "125",
          mfrNo: "125",
          selected: false
        },
        {
          integratedDeviceCardNumber: "114",
          financialNumber: "001009",
          startDate: "1901-01-01",
          deviceLabel: "演示用设备",
          deviceOriginalValue: 100,
          usageLocation: "111",
          mfr: "111",
          mfrNo: "111",
          selected: false
        }
      ]
    },

    // 初始值
    initialMode: {
      type: String,
      default: "single",
      validator: value => ["single", "multiple"].includes(value)
    },
    initialSelected: {
      type: Array,
      default: () => []
    },

    // 配置选项
    allowCancel: {
      type: Boolean,
      default: true
    },
    showStatus: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      selectionOb: {},
      selectionMode: this.initialMode,
      selectedCategory: "all",
      searchTerm: "",
      selectedDevices: [...this.initialSelected],
      // 新增：存储所有设备的选中状态（与 row.selected 同步）
      deviceSelectStatus: {}
    };
  },
  mounted() {
    // 初始化：根据 initialSelected 设为 row.selected = true
    this.devices.forEach(device => {
      device.selected = this.initialSelected.includes(
        device.integratedDeviceCardNumber
      );
    });
    // 同步到 deviceSelectStatus
    this.syncSelectStatus();
  },
  computed: {
    filteredDevices() {
      let filtered = [...this.devices]; // 深拷贝避免修改原数据
      // 原有分类筛选、搜索筛选逻辑不变（保留你的代码）
      if (this.selectedCategory !== "all") {
        const categoryMap = {
          /* 你的分类映射不变 */
        };
        const categoryName = categoryMap[this.selectedCategory];
        filtered = filtered.filter(
          device => device.deviceLabel === categoryName
        );
      }
      if (this.searchTerm) {
        const term = this.searchTerm.toLowerCase();
        filtered = filtered.filter(
          device =>
            device.integratedDeviceCardNumber.toLowerCase().includes(term) ||
            device.deviceLabel.toLowerCase().includes(term)
        );
      }
      return filtered;
    },
    // filteredDevices() {
    //   let filtered = this.devices;
    //   console.log("this.devices", this.devices);
    //   // 按分类筛选（适配设备的deviceLabel字段）
    //   if (this.selectedCategory !== "all") {
    //     const categoryMap = {
    //       demo: "演示用设备",
    //       production: "生产设备",
    //       electronic: "电子设备",
    //       transport: "运输工具",
    //       instrument: "仪器及试验设备",
    //       tools: "工具仪器及生产用品",
    //       road: "一期扩建道路",
    //       land: "土地、使用权",
    //       decoration: "装修工程",
    //       office: "办公设备",
    //       other: "其他固定资产",
    //       building: "建筑物",
    //       server: "x86服务器"
    //     };
    //     const categoryName = categoryMap[this.selectedCategory];
    //     filtered = filtered.filter(device => {
    //       console.log("device", device);
    //       return device.deviceLabel === categoryName;
    //     });
    //   }

    //   // 按搜索词筛选（适配设备的编号/名称字段）
    //   if (this.searchTerm) {
    //     const term = this.searchTerm.toLowerCase();
    //     filtered = filtered.filter(
    //       device =>
    //         device.integratedDeviceCardNumber.toLowerCase().includes(term) ||
    //         device.deviceLabel.toLowerCase().includes(term)
    //     );
    //   }

    //   return filtered;
    // },
    getHeight() {
      let upDownH = 0;
      this.$nextTick(() => {
        let head_h = document.getElementsByTagName("header");
        let foot_h = document.getElementsByClassName("footer");
        if (head_h) {
          upDownH = head_h[0].offsetHeight;
        }
        if (foot_h) {
          upDownH += foot_h[0].offsetHeight;
        }
        let content = document.querySelector(".content");
        if (content) {
          content.style.height = `calc(80vh - ${upDownH}px)`;
        }
      });
      return upDownH;
    }
  },
  watch: {
    initialSelected(newVal) {
      this.selectedDevices = [...newVal];
    },
    initialMode(newVal) {
      this.selectionMode = newVal;
    }
  },

  methods: {
  
    select(selection, row) {
      console.log("e-1", selection, row);
      // if (this.selectionMode === "single") {
      //   // 单选模式：清空所有选中，只保留当前行
      //   this.$refs.deviceTable.clearSelection(); // 先清空所有选中项
      //   this.$refs.deviceTable.toggleRowSelection(row, true); // 仅选中当前行
      //   this.selectedDevices = [row.integratedDeviceCardNumber]; // 更新选中ID数组
      // } else {
      //   // 多选模式：同步所有选中项的ID
      //   this.selectedDevices = selection.map(
      //     item => item.integratedDeviceCardNumber
      //   );
      // }
      console.log("this.selectedDevices", this.selectedDevices);
      //  this.$emit("selection-change", this.selectedDevices);
    },
    selectAll(e) {
      console.log("e-2", e);
      // this.$refs.deviceTable.clearSelection();
    },
    changeMode(mode) {
      this.selectionMode = mode;
      this.$refs.deviceTable.clearSelection();
      console.log("[this.selectedDevices", this.selectedDevices);
      // 单选模式下只保留第一个选中项
      // if (mode === "single" && this.selectedDevices.length > 1) {
      //   this.selectedDevices = [this.selectedDevices[0]];
      // }
      this.selectedDevices = [];
      this.$emit("mode-change", mode);
    },

    selectCategory(categoryId) {
      this.selectedCategory = categoryId;
      this.$emit("category-change", categoryId);
    },

    isDeviceSelected(deviceId) {
      return this.selectedDevices.includes(deviceId);
    },

    toggleDevice(deviceId) {
      const device = this.devices.find(
        d => d.integratedDeviceCardNumber === deviceId
      );
      if (device?.disabled) return;

      if (this.selectionMode === "single") {
        // 单选：直接替换选中项
        this.selectedDevices = [deviceId];
      } else {
        // 多选：切换选中状态
        const index = this.selectedDevices.indexOf(deviceId);
        if (index > -1) {
          this.selectedDevices.splice(index, 1);
        } else {
          this.selectedDevices.push(deviceId);
        }
      }
      console.log("[this.selectedDevices]", this.selectedDevices);
      this.$emit("selection-change", this.selectedDevices);
    },

    confirmSelection() {
      if (this.selectedDevices.length === 0) return;
      const selectedDevicesData = this.devices.filter(device =>
        this.selectedDevices.includes(device.integratedDeviceCardNumber)
      );
      this.$emit("confirm", {
        deviceIds: this.selectedDevices,
        devices: selectedDevicesData,
        mode: this.selectionMode
      });
    },

    handleCancel() {
      this.$emit("cancel");
    },

    clearSelection() {
      this.selectedDevices = [];
      this.$emit("selection-change", this.selectedDevices);
    },

    setSelection(deviceIds) {
      if (this.selectionMode === "single" && deviceIds.length > 1) {
        console.warn("单选模式下只能选择一个设备，将使用第一个设备ID");
        this.selectedDevices = [deviceIds[0]];
      } else {
        this.selectedDevices = [...deviceIds];
      }
      this.$emit("selection-change", this.selectedDevices);
    },
    // 同步 row.selected 到 selectedDevices
    syncSelectStatus() {
      this.selectedDevices = this.devices
        .filter(device => device.selected)
        .map(device => device.integratedDeviceCardNumber);
    },

    // 自定义复选框 change 事件（核心单选/多选逻辑）
    handleSelectionChange(row) {
      console.log('row',row);
      if (this.selectionMode === "single") {
        // 单选模式：清空所有选中，仅保留当前行
        this.devices.forEach(device => {
          device.selected =
            device.integratedDeviceCardNumber ===
            row.integratedDeviceCardNumber;
        });
      } else {
        // 多选模式：仅切换当前行的选中状态
        // row.selected = !row.selected;
      }
      // 同步选中设备ID数组
      this.syncSelectStatus();
      this.$emit("selection-change", this.selectedDevices);
    },

    // 新增：全选/取消全选功能（如果需要）
    toggleAllSelection() {
      const isAllSelected =
        this.selectedDevices.length === this.filteredDevices.length;
      this.filteredDevices.forEach(device => {
        device.selected = !isAllSelected;
      });
      this.syncSelectStatus();
      this.$emit("selection-change", this.selectedDevices);
    },

    // 切换模式时，清空所有选中状态
    changeMode(mode) {
      this.selectionMode = mode;
      // 清空所有选中
      this.devices.forEach(device => {
        device.selected = false;
      });
      this.syncSelectStatus();
      this.$emit("mode-change", mode);
    },

    // 其他原有方法（selectCategory、confirmSelection 等）不变
    confirmSelection() {
      if (this.selectedDevices.length === 0) return;
      const selectedDevicesData = this.devices.filter(device =>
        this.selectedDevices.includes(device.integratedDeviceCardNumber)
      );
      this.$emit("confirm", {
        deviceIds: this.selectedDevices,
        devices: selectedDevicesData,
        mode: this.selectionMode
      });
    }
  }
};
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Segoe UI", "Microsoft YaHei", sans-serif;
}

.container {
  max-height: 80vh;
  width: 70%;
  max-width: 1000px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

header {
  padding: 24px 30px;
  border-bottom: 1px solid #eaeef2;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(135deg, #095b90, #6a82fb);
  color: white;
}

h1 {
  font-size: 24px;
  font-weight: 600;
}

.header-controls {
  display: flex;
  align-items: center;
  gap: 20px;
}

.selection-mode {
  display: flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 6px;
  padding: 5px;
}

.mode-btn {
  padding: 8px 16px;
  border: none;
  background: transparent;
  color: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.mode-btn.active {
  background: rgba(255, 255, 255, 0.3);
  font-weight: 500;
}

.search-box {
  position: relative;
  width: 300px;
}

.search-box /deep/ .el-input__inner {
  width: 100%;
  padding: 12px 20px 12px 45px;
  border: none;
  border-radius: 30px;
  background: rgba(255, 255, 255, 0.9);
  font-size: 14px;
  transition: all 0.3s;
}

.search-box /deep/ .el-input__inner:focus {
  outline: none;
  box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.5);
  background: white;
}

.search-icon {
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translateY(-50%);
  color: #6a82fb;
}

.content {
  display: flex;
  min-height: 500px;
  box-sizing: border-box;
}

.sidebar {
  width: 260px;
  background: #f8fafc;
  border-right: 1px solid #eaeef2;
  padding: 25px 0;
  overflow-y: auto;
}

.category-list {
  list-style: none;
}

.category-item {
  padding: 14px 30px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  font-size: 15px;
  color: #555;
}

.category-item:hover {
  background: #edf2ff;
  color: #6a82fb;
}

.category-item.active {
  background: #e8eeff;
  color: #6a82fb;
  border-right: 3px solid #6a82fb;
  font-weight: 500;
}

.category-item i {
  margin-right: 12px;
  font-size: 18px;
}

.main-content {
  flex: 1;
  padding: 25px 30px;
  overflow-y: auto;
}

.devices-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
}

.devices-count {
  color: #666;
  font-size: 15px;
}

/* 表格相关样式（复用Element UI默认样式，这里补充微调） */
.el-table {
  --el-table-row-hover-bg-color: #edf2ff;
}
.el-table::before {
  height: 0;
}

.no-devices {
  text-align: center;
  padding: 40px;
  color: #888;
  font-size: 16px;
}

.footer {
  padding: 20px 30px;
  border-top: 1px solid #eaeef2;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #f8fafc;
}

.selected-info {
  color: #666;
  font-size: 14px;
}

.selected-count {
  font-weight: 600;
  color: #6a82fb;
}

.footer-buttons {
  display: flex;
  gap: 12px;
}

.cancel-btn {
  background: #f8f9fa;
  color: #666;
  border: 1px solid #ddd;
  padding: 12px 24px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s;
}

.cancel-btn:hover {
  background: #e9ecef;
  border-color: #adb5bd;
}

.confirm-btn {
  background: #6a82fb;
  color: white;
  border: none;
  padding: 12px 30px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 15px;
  font-weight: 500;
  transition: all 0.2s;
}

.confirm-btn:hover:not(:disabled) {
  background: #5a72e5;
  box-shadow: 0 4px 10px rgba(106, 130, 251, 0.3);
}

.confirm-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
  box-shadow: none;
}
</style>